<?php

// 收藏功能

namespace app\shop\controller;

use think\Db;
use think\Request;
use think\Session;
use think\Controller;
use app\shop\model\Shop as ShopModel;
use app\shop\model\ShopGoods as ShopGoodsModel;
use app\shop\model\MemberCollect as MemberCollectModel;

class Collect extends Controller
{
    /**
     * 收藏 取消收藏
     * @param Request $request
     * @param ShopModel $shop
     * @param ShopGoodsModel $shopGoods
     * @param MemberCollectModel $memberCollect
     * @return array
     */
    public function member_collect(Request $request, ShopModel $shop, ShopGoodsModel $shopGoods, MemberCollectModel $memberCollect)
    {
        if ($request->isPost()) {
            //  获取参数
            $id = $request->post('id');
            // 1 商品  2店铺
            $type = $request->post('type');
            // 会员ID
            $member_id = Session::get('member_id');
            if (empty($member_id)) return ['code' => 402, 'message' => '请先登录！'];

            $status = $memberCollect->where(['type_id' => $type, 'collect_id' => $id, 'member_id' => $member_id])->find();

            Db::startTrans();
            //启动事务
            try {

                if ($status) { //取消收藏
                    $memberCollect::destroy($status['id']);

                    if ($type == 1) {  //收藏商品
                        $shopGoods->where('id', $id)->setDec('collect');  //收藏数减1
                    } else {
                        $shop->where('member_id', $id)->setDec('collect_number');
                    }

                    Db::commit();

                    return ['code' => 100, 'message' => '取消收藏成功'];
                } else {  //收藏
                    $memberCollect->isUpdate(false)->save(['type_id' => $type, 'collect_id' => $id, 'member_id' => $member_id, 'create_time' => time()]);

                    if ($type == 1) {  //收藏商品
                        $shopGoods->where('id', $id)->setInc('collect');  //收藏数加1
                    } else {
                        $shop->where('member_id', $id)->setInc('collect_number');
                    }

                    Db::commit();

                    return ['code' => 200, 'message' => '收藏成功'];
                }
            } catch (\Exception $e) {

                Db::rollback();

                return ['code' => 0, 'message' => '网络繁忙,请重试'];
            }
        }
    }
}